package Controller;


import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DAO.DAOFactory;
import DAO.RankDAO;
import Model.*;

/**
 * Servlet implementation class RankDetail
 */
@WebServlet("/RankDetail")
public class RankDetail extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RankDetail() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		Authenticate(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		Authenticate(request,response);
	}
	
	protected void Authenticate (HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		//Authenticate before starting process
		if ( LoginAdmin.CheckObject(request, response) ) {
			doProcess(request,response);
		} else {	//Otherwise Authentication Object not found
			response.sendRedirect(LoginAdmin.LOGIN_CONTROL);
		}
	}	

	protected void doProcess(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		String editRankId = request.getParameter("EditRankId");
		String isSubmit = request.getParameter("IsSubmit");
		String lastRankName = request.getParameter("RankName");
		String lastTotalDays = request.getParameter("TotalDays");
		String rankNameErrorMsg = "";
		String totalDaysErrorMsg = "";
		boolean validatePass = false;
		
		//Edits should be submitted to Edits
		String actionTargetTail = "";
		String pageTitle = "";
		if (editRankId == null) {	//If this is "Add"
			pageTitle = "Add new Rank";
		} else {					//Otherwise this is "Edit", add tail
			actionTargetTail = "?EditRankId="+editRankId;
			pageTitle = "Editting Rank: "+editRankId;
		}
		
		//Functions for First Load
		if (isSubmit == null)		//If this is first load
		{
			validatePass = false;
			if (editRankId == null)	//If this is "Add Rank"
			{
				lastRankName = "";	//Last Values are empty strings
				lastTotalDays = "";
			}
			else					//Otherwise this is "Edit Rank"
			{
				RankDAO rankDAO = 	//get DAO
						DAOFactory.getInstance().getRankDAO();
				RankBean rank = new RankBean();
				int rankInt = Integer.parseInt(editRankId);
				try{
					rank = rankDAO.findByRankID(rankInt);
				} catch (Exception e) {
					e.printStackTrace();
				}
				lastRankName = rank.getRank_name();
				Integer tempI = rank.getTotal_days();
				lastTotalDays = tempI.toString();
			}
		}
		
		//Functions for Submission
		else	//Otherwise this is submission
		{		//Start Validation
			validatePass = true;
			if (lastRankName.length() == 0)
			{ 
				rankNameErrorMsg = "Please enter a Rank Name";
				validatePass = false;
			}
			if (lastTotalDays.length() == 0)
			{ 
				totalDaysErrorMsg = "Please enter the amount of Annual Leave";
				validatePass = false;
			} else if (! lastTotalDays.matches("[0-9]+") )
			{
				totalDaysErrorMsg = "Annual Leave must be a positive number";
				validatePass = false;				
			}
		}

		//Finally, decide whether to stay on this page or go back to List
		if (validatePass) {					//If Validation was successful
			RankDAO rankDAO = 				//get DAO
					DAOFactory.getInstance().getRankDAO();
			RankBean rank = new RankBean();
			rank.setRank_name(lastRankName);
			rank.setTotal_days( Integer.parseInt(lastTotalDays) );
			int newRank = 0;
			if (editRankId == null)			//If this is "Add Rank"
			{
				int tempI = 1;					//Generate Rank ID
				try {
					tempI = rankDAO.findNextRank();
				} catch (Exception e) {
					e.printStackTrace();
				}
				rank.setRank_id(tempI);
				try {
					rankDAO.addRank(rank);	//Add to DB
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			else							//Otherwise this is "Edit Rank"
			{
				rank.setRank_id( Integer.parseInt(editRankId) );
				try {
					rankDAO.updateRank(rank);	//Update to DB
				} catch (Exception e) {
					e.printStackTrace();
				}				
			}	
			response.sendRedirect("RankList");		//Redirect here
		} else {																						//Otherwise Login failed, or this is first load
			request.setAttribute("PageTitle", pageTitle);
			request.setAttribute("ActionTargetTail", actionTargetTail);
			request.setAttribute("LastRankName", lastRankName);
			request.setAttribute("LastTotalDays", lastTotalDays);
			request.setAttribute("RankNameErrorMsg", rankNameErrorMsg);
			request.setAttribute("TotalDaysErrorMsg", totalDaysErrorMsg);
			RequestDispatcher rd = request.getRequestDispatcher("RankDetail.jsp");
			rd.forward(request, response);												//Dispatch to View
		}	
	}
}
